<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'

const { add, update } = usePermission()
defineOptions({ name: 'Modal' })

interface Props {
  /** 弹窗可见性 */
  visible: boolean
  /**
   * 弹窗类型
   * add: 新增
   * edit: 编辑
   */
  type?: 'add' | 'edit'
  /** 编辑的表格行数据 */
  model?: PermissionModel | null
  /** 重新加载表格数据 */
  load: Function
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'load'): void
}

const formRef = ref<HTMLElement & FormInst>()
const emit = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {
  type: 'add',
})

watch(
  () => props.visible,
  (newValue) => {
    if (newValue) {
      if (props.type == 'add') {
        Object.assign(formModel, defaultModel())
      } else if (props.type == 'edit' && props.model) {
        Object.assign(formModel, props.model)
      }
    }
  },
)
//是否显示弹窗
const modalVisible = computed({
  get() {
    return props.visible
  },
  set(visible) {
    emit('update:visible', visible)
  },
})

const title = computed(() => {
  const titles: Record<ModalType, string> = { add: '添加权限', edit: '编辑权限' }
  return titles[props.type]
})

const defaultModel = (): PermissionModel => ({ name: '', description: '' })

const formModel = reactive<PermissionModel>(defaultModel())

const rules: FormRules = {
  name: { required: true, message: '输入名称' },
  description: { required: true, message: '输入描述' },
}

//关闭弹窗
const closeModal = () => (modalVisible.value = false)

//提交数据
async function handleSubmit() {
  await formRef.value?.validate()
  const { success } = props.type == 'add' ? await add(formModel) : await update(formModel)
  if (success) {
    props.load()
    closeModal()
  }
}
</script>

<template>
  <n-modal v-model:show="modalVisible" preset="card" :title="title" class="max-w-md">
    <n-form ref="formRef" :label-width="80" :model="formModel" :rules="rules">
      <n-form-item label="名称" path="name">
        <n-input v-model:value="formModel.name" placeholder="请输入名称" va></n-input>
      </n-form-item>
      <n-form-item label="描述" path="description">
        <n-input type="textarea" v-model:value="formModel.description" placeholder="请输入描述" />
      </n-form-item>

      <n-space justify="end">
        <n-button @click="closeModal">取消</n-button>
        <n-button type="primary" @click="handleSubmit">确定</n-button>
      </n-space>
    </n-form>
  </n-modal>
</template>

<style lang="scss" scoped></style>
